import {promiseRequest, getOpenId ,bezier,go} from "../../../utils/index";
import { imgBaseUrl } from "../../../utils/config";
const app = getApp()
Page({
  data: {
    imgBaseUrl:imgBaseUrl,
    menuTypeList:[],
    menuTypeTab:0,
    selectedMenuType:{},
    outFoodList:[],
    outFoodTab:0,
    selectedoutfoodtype:{},
    outFoodMainTab:0,
    outFoodMainList:[],
    TabCur: 0,
    MainCur: 0,
    VerticalNavTop: 0,
    list: [],
    load: true,
    buynum:0,
    selectedGoods:[],
    hide_good_box: true,
  },
  onLoad() {
    this.busPos = {};
    this.busPos['x'] = app.globalData.ww/6;
    this.busPos['y'] = app.globalData.hh - 30;  
    //菜单类型初始化数据:外卖，堂食
    let menuTypeList = [{}]; 
    menuTypeList[0]={};menuTypeList[0].name="外卖";menuTypeList[0].typeCode=0;
    menuTypeList[1]={};menuTypeList[1].name="堂食";menuTypeList[1].typeCode=1;
    this.setData({
      menuTypeList: menuTypeList,
      selectedMenuType:menuTypeList[0]
    })
    //外卖菜单类型数据初始化
    this.getMenusByType();
    this.getShoppingCartNum();
    // let outFoodMainList = [{}];
    // outFoodMainList[0]={};outFoodMainList[0].id=1;outFoodMainList[0].name="鸡块面";outFoodMainList[0].price=11.0;outFoodMainList[0].img="https://ossweb-img.qq.com/images/lol/web201310/skin/big10001.jpg";
    // this.setData({
    //   outFoodMainList: outFoodMainList
    // })

    // let list = [{}];
    // for (let i = 0; i < 26; i++) {
    //   list[i] = {};
    //   list[i].name = String.fromCharCode(65 + i);
    //   list[i].id = i;
    // }
    // this.setData({
    //   list: list,
    //   listCur: list[0]
    // })
  },
  onReady() {
    wx.hideLoading()
  },
  menuTabSelect(e) {
    var selectedMenuType = this.data.menuTypeList[e.currentTarget.dataset.id];
    this.setData({
      menuTypeTab: e.currentTarget.dataset.id,
      selectedMenuType:selectedMenuType
    })
  },
  outFoodTabSelect(e) {
    var selectedoutfoodtype =  this.data.outFoodList[e.currentTarget.dataset.id];
    if(e.currentTarget.dataset.id!=this.data.outFoodTab){
      this.getGoodsByType(selectedoutfoodtype.id);
    }
    this.setData({
      outFoodTab: e.currentTarget.dataset.id,
      outFoodMainTab: e.currentTarget.dataset.id,
      VerticalNavTop: (e.currentTarget.dataset.id - 1) * 50,
      selectedoutfoodtype:selectedoutfoodtype
    })
  },
  VerticalMain(e) {
    let that = this;
    let list = this.data.list;
    let tabHeight = 0;
    if (this.data.load) {
      for (let i = 0; i < list.length; i++) {
        let view = wx.createSelectorQuery().select("#main-" + list[i].id);
        view.fields({
          size: true
        }, data => {
          list[i].top = tabHeight;
          tabHeight = tabHeight + data.height;
          list[i].bottom = tabHeight;     
        }).exec();
      }
      that.setData({
        load: false,
        list: list
      })
    }
    let scrollTop = e.detail.scrollTop + 20;
    for (let i = 0; i < list.length; i++) {
      if (scrollTop > list[i].top && scrollTop < list[i].bottom) {
        that.setData({
          VerticalNavTop: (list[i].id - 1) * 50,
          TabCur: list[i].id
        })
        return false
      }
    }
  },
  /**
   * 根据商品分类类型获取指定类型下的商品分类
   */
  getMenusByType(){
    var param = {}; param.shId = app.globalData.shId;param.typeCode=this.data.selectedMenuType.typeCode;
    let requestObj = {
      url: '/wxa/shoptypeApi/getcacheShopType',
      method: 'post',
      dataobj: param,
    };
    var that = this;
    promiseRequest(requestObj).then((res) => {
      if (res.code == 200) {
        var selectedoutfoodtype =  res.data[0];
        that.getGoodsByType(selectedoutfoodtype.id);
        that.setData({
          outFoodList: res.data,
          selectedoutfoodtype:selectedoutfoodtype
        })
      }
    }).catch((errMsg) => {
    });
  },
  /**
   * 根据shId和商品类型查询改类型下的商品信息
   */
  getGoodsByType(typeId){
    var param = {}; param.shId = app.globalData.shId;param.type1Id=typeId;
    let requestObj = {
      url: '/wxa/shopgoodsApi/getcacheShopGoodsByType',
      method: 'post',
      dataobj: param,
    };
    var that = this;
    promiseRequest(requestObj).then((res) => {
      if (res.code == 200) {
        let result = that.restoreSelectedGoodNum(res.data);
        that.setData({
          outFoodMainList: result
        })
      }
    }).catch((errMsg) => {
    });
  },

  handleAdd(e){
    this.showBezier(e);
    let selectedGoods = this.data.selectedGoods;
    let item = e.currentTarget.dataset.item;
    let indx = e.currentTarget.dataset.index;
    item.num = item.num ==undefined?0:item.num;
    item.num = item.num + 1;
    let num = 'outFoodMainList['+indx+'].num';
    let index = selectedGoods.findIndex(gd => gd.id === item.id);
    if (index === -1) {
      selectedGoods.push(item);
    } else {
      selectedGoods[index].num += 1
    }
    this.setData({
      buynum: this.data.buynum+1,
      [num]:item.num,
      selectedGoods:selectedGoods
    })
    //持久化购物车商品信息
    var that = this;
    var param = {}; 
    param.shId = app.globalData.shId;
    param.openId = getOpenId();
    let shopcart = {};shopcart.openId = getOpenId();shopcart.shId=app.globalData.shId;
    shopcart.goodId = item.id;shopcart.goodName = item.goodName;shopcart.sellerPrice = item.sellerPrice;shopcart.goodImages = item.goodImages;shopcart.num = 1;
    param.data = shopcart;
    let shopcarts = wx.getStorageSync('shopcarts');
    shopcarts = shopcarts ? JSON.parse(shopcarts) : [];
    let requestObj = {
      url: '/wxa/shopcartApi/addShopCartByOpenId',
      method: 'post',
      dataobj: param,
    };
    promiseRequest(requestObj).then((res) => {
      if (res.code == 200) {
        shopcarts.push(shopcart);
        wx.setStorageSync('shopcarts', JSON.stringify(shopcarts));
      }
    }).catch((errMsg) => {
    });
  },
  handleReduce(e){
    let selectedGoods = this.data.selectedGoods;
    let item = e.currentTarget.dataset.item;
    let indx = e.currentTarget.dataset.index;
    item.num = item.num ==undefined?0:item.num;
    if(item.num==0){
      item.num = 0;
    }else{
      item.num = item.num-1;
    }
    let num = 'outFoodMainList['+indx+'].num';
    let index = selectedGoods.findIndex(gd => gd.id === item.id);
    let num_s = selectedGoods[index].num;
    num_s > 1 ? selectedGoods[index].num = num_s - 1 : selectedGoods.splice(index, 1);
    this.setData({
      buynum: this.data.buynum-1,
      [num]:item.num,
      selectedGoods:selectedGoods
    })
    //删除购物车信息
    let shopcarts = wx.getStorageSync('shopcarts');
    shopcarts = shopcarts ? JSON.parse(shopcarts) : [];
    var param = {}; 
    param.shId = app.globalData.shId;
    param.openId = getOpenId();
    param.goodId = item.id;
    let requestObj = {
      url: '/wxa/shopcartApi/deleteShopCartByGoodId',
      method: 'post',
      dataobj: param,
    };
    promiseRequest(requestObj).then((res) => {
      if (res.code == 200) {
        let index = shopcarts.findIndex(gd => gd.id === item.id);
        shopcarts.splice(index, 1);
        wx.setStorageSync('shopcarts', JSON.stringify(shopcarts));
      }
    }).catch((errMsg) => {
    });
  },
  restoreSelectedGoodNum(goods){
    let shopcarts = wx.getStorageSync('shopcarts');
		shopcarts = shopcarts ? JSON.parse(shopcarts) : [];
     for(var i = 0 ; i < goods.length;i++){
         let gditem = goods[i];
         for(var j = 0 ;j<shopcarts.length;j++){
           let shopcart = shopcarts[j];
            if(gditem.id == shopcart.goodId){
              gditem.num =  shopcart.num
            }
         }
         return goods;
     }
  },
  showBezier(e) {
    // 如果good_box正在运动
    if (!this.data.hide_good_box) return;
    this.finger = {};
    var topPoint = {};
    this.finger['x'] = e.touches[0].clientX;
    this.finger['y'] = e.touches[0].clientY;
    if (this.finger['y'] < this.busPos['y']) {
      topPoint['y'] = this.finger['y'] - 150
    } else {
      topPoint['y'] = this.busPos['y'] - 150; 
    }   
    topPoint['x'] = Math.abs(this.finger['x'] - this.busPos['x']) / 2;
    if (this.finger['x'] > this.busPos['x']) {
      topPoint['x'] = (this.finger['x'] - this.busPos['x']) / 2 + this.busPos['x'];
    } else {
      topPoint['x'] = (this.busPos['x'] - this.finger['x']) / 2 + this.finger['x'];
    }
    this.linePos = bezier([this.finger, topPoint, this.busPos], 20);
    console.log('this.linePos',this.linePos)
    this.startAnimation();
  },
  startAnimation() {
    var index = 0,
    that = this,
    bezier_points = that.linePos['bezier_points'],
    len = bezier_points.length - 1;
    this.setData({
      hide_good_box: false,
      bus_x: that.finger['x'],
      bus_y: that.finger['y']
    })
    this.timer = setInterval(function () {
      index++;
      that.setData({
        bus_x: bezier_points[index]['x'],
        bus_y: bezier_points[index]['y']
      })
      if (index >= len) {
        clearInterval(that.timer);
        that.setData({
          hide_good_box: true,
        })
      }
    }, 25)
  },
  /**
   * 获取本地缓存的购物车商品个数
   */
  getShoppingCartNum(){
    let shopcarts = wx.getStorageSync('shopcarts');
    shopcarts = shopcarts ? JSON.parse(shopcarts) : [];
    let allNum = 0;
		for (var i = 0; i < shopcarts.length; i++) {
			let shopcart = shopcarts[i];
			allNum+=shopcart.num;
		}
		this.setData({
			buynum:allNum
		})
	},
  //打开购物车页面
  gotoCart(){
    go(1,'/pages/tabar/shoppingcart/shoppingcart');
  }
})